package de.tsajar.es.damage;

import com.simsilica.es.Entity;
import com.simsilica.es.EntityData;
import com.simsilica.es.EntityId;
import com.simsilica.es.EntitySet;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Eike Foede
 */
public class DamageSystem {

    EntityData ed;
    EntitySet damages;
    EntitySet healthes;

    public DamageSystem(EntityData ed) {
	this.ed = ed;
	damages = ed.getEntities(DamageComponent.class);
	healthes = ed.getEntities(HealthComponent.class);
    }

    public void execute() {
	damages.applyChanges();
	healthes.applyChanges();

	Map<EntityId, Float> damageSummary = new HashMap();

	for (Entity e : damages) {

	    DamageComponent dc = e.get(DamageComponent.class);
	    float dmgSum = 0;

	    if (damageSummary.containsKey(dc.getTarget())) {
		dmgSum = damageSummary.get(dc.getTarget());
	    }

	    dmgSum += dc.getDamage();

	    damageSummary.put(dc.getTarget(), dmgSum);

	    ed.removeEntity(e.getId());
	}
	for (EntityId e : damageSummary.keySet()) {
	    float damage = damageSummary.get(e);

	    Entity entity = healthes.getEntity(e);
	    if (entity != null) {
		HealthComponent hc = entity.get(HealthComponent.class);
		float newLife = hc.getHealth() - damage;

		if (newLife < 0) {
		    ed.removeComponent(e, HealthComponent.class);
		    ed.setComponent(e, new DeadComponent());
		} else {
		    entity.set(new HealthComponent(newLife));
		}
	    }
	}

    }
}
